//
//  AccountSettingViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/15.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit
import MobileCoreServices

class AccountSettingViewController: UIViewController, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var hud: MBProgressHUD?
    var nick = ""
    var userImg: UIImage?
    var imgChanged = false
    
    @IBOutlet weak var nickTextField: UITextField!
    @IBOutlet weak var accountLabel: UILabel!
    @IBOutlet weak var userImgButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        if (DBUtils.mem.imgURL != "") {
            DBUtils.getImageFromFile(DBUtils.mem.imgURL, successHandler: { (_imageURL, _image) -> Void in
                if (_imageURL == DBUtils.mem.imgURL) {
                    self.userImgButton.setBackgroundImage(_image, forState: UIControlState.Normal)
                }
            })
        }
        
        if (DBUtils.mem.nickName != "") {
            self.nickTextField.text = DBUtils.mem.nickName
        }
        self.accountLabel.text = "登录账号：" + DBUtils.mem.loginName
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func backButtonPressed(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
        
    }
    
    @IBAction func saveButtonPressed(sender: AnyObject) {
        
        nick = self.nickTextField.text
        if (count(nick) < 1 || count(nick) > 8) {
            ViewUtils.popMessage(self, title: "", message: "昵称长度应为1-8个字符")
            return
        }
        
        self.startIndicator()
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            var a: [String: AnyObject]?
            if (self.imgChanged && self.userImg != nil) {
                let imgStr = StringUtils.getHexStrFromImage(self.userImg!)
                a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "nickname": self.nickTextField.text, "headimg": imgStr]
            } else {
                a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "nickname": self.nickTextField.text]
            }
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLModifyInfo(), parameters: a, view: self.view, responseHandler: self.stopIndicator, successHandler: self.save)
        })
    }
    
    @IBAction func imgButtonPressed(sender: AnyObject) {
        var device : UIDevice = UIDevice.currentDevice()
        var systemVersion = device.systemVersion
        var iosVerion = (systemVersion as NSString).floatValue
        if(iosVerion < 8.0) {
            let actionSheet = UIActionSheet()
            actionSheet.delegate = self
            actionSheet.addButtonWithTitle("拍照")
            actionSheet.addButtonWithTitle("从相册选择")
            actionSheet.addButtonWithTitle("取消")
            actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1
            actionSheet.showFromRect(self.view.bounds, inView: self.view, animated: true)
        } else {
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
            alert.addAction(UIAlertAction(title: "拍照", style:UIAlertActionStyle.Default, handler: takePicture))
            alert.addAction(UIAlertAction(title: "从相册选择", style:UIAlertActionStyle.Default, handler: getImageFromLib))
            alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
    
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        switch (buttonIndex) {
        case 0:
            takePicture(nil)
        case 1:
            getImageFromLib(nil)
        default:
            return
        }
    }
    
    func takePicture(alertAction: UIAlertAction!) {
        var picker = UIImagePickerController()
        if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
            picker.sourceType = UIImagePickerControllerSourceType.Camera
        } else {
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        }
        picker.mediaTypes = [kUTTypeImage]
        picker.allowsEditing = true
        picker.delegate = self
        
        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    func getImageFromLib(alertAction: UIAlertAction!) {
        var picker = UIImagePickerController()
        picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        picker.allowsEditing = true
        picker.mediaTypes = [kUTTypeImage]
        picker.delegate = self
        
        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        userImg = info["UIImagePickerControllerEditedImage"] as? UIImage
        imgChanged = true
        userImgButton.setBackgroundImage(userImg, forState: UIControlState.Normal)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    //MARK: - 网络回调函数
    
    func startIndicator() {
        hud = MBProgressHUD(view: self.view)
        self.view.addSubview(hud!)
        hud?.labelText = "努力保存中.."
        hud?.show(true)
    }
    
    func stopIndicator() {
        hud?.hide(false)
    }
    
    func save(json: JSON) {
        let imgUrl = json["headimg"].string
        if let a = imgUrl {
            DBUtils.mem.imgURL = a
            DBUtils.saveImageToFile(a, image: userImg!)
        }
        DBUtils.mem.nickName = nick
        self.navigationController?.popViewControllerAnimated(true)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
